package com.xatz.scanner

import android.Manifest
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.widget.addTextChangedListener
import com.pgyersdk.update.DownloadFileListener
import com.pgyersdk.update.PgyUpdateManager
import com.pgyersdk.update.UpdateManagerListener
import com.pgyersdk.update.javabean.AppBean
import com.xatz.scanner.databinding.ActivityMainBinding
import com.xatz.scanner.databinding.DialogExitLoginBinding
import timber.log.Timber
import java.io.File


private const val REQUEST_CODE_EXTERNAL_STORAGE_PERMISSIONS = 1

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var mBinding: ActivityMainBinding

    private lateinit var sharedPreferences: SharedPreferences

    private lateinit var edit: SharedPreferences.Editor

    private val receiver = HomeKeyEventReceiver()

    //用于存放上一点击返回键的时刻
    private var mExitTime: Long = 0
    private var userAccount = ""
    private var userBz = ""

    @SuppressLint("CommitPrefEdits")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedPreferences = getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
        edit = sharedPreferences.edit()
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.tvText.setOnClickListener {
//            startActivity(Intent(this, SalesActivity::class.java))
        }
        mBinding.llHomeFre.setOnClickListener(this)
        mBinding.clFourLayout.setOnClickListener(this)
        mBinding.cvExit.setOnClickListener(this)
        mBinding.llSelect.setOnClickListener(this)
        mBinding.clVersion.setOnClickListener(this)
        mBinding.tvText.setOnClickListener(this)
        mBinding.llTwoHomeFre.setOnClickListener(this)
        mBinding.llMovingStacking.setOnClickListener(this)
        mBinding.clDoormanReviewLayout.setOnClickListener(this)
        mBinding.llSoldStockOut.setOnClickListener(this)
        mBinding.llMovingStacking2.setOnClickListener(this)
        mBinding.tvVersion.text = BuildConfig.VERSION_NAME
        registerReceiver(receiver, IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))

        userAccount = getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
            .getString(Constant.userAccount, "").toString()
        userBz = getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
            .getString(Constant.userBz, "").toString()
        Timber.e(userAccount)
        when (userBz) {
            "FLM" -> {
                mBinding.llHomeFre.visibility = View.VISIBLE
                mBinding.clFourLayout.visibility = View.VISIBLE
                mBinding.llTwoLayout.visibility = View.GONE
            }
            "GPB", "GPK", "TKB", "TKY" -> {
                mBinding.llMovingStacking2.visibility = View.VISIBLE
            }
            "HTM", "ZTM" -> {
                mBinding.llHomeFre.visibility = View.VISIBLE
            }
            "KFB" -> {
                mBinding.llTwoHomeFre.visibility = View.VISIBLE
                mBinding.llMovingStacking2.visibility = View.VISIBLE
                mBinding.llSelect.visibility = View.VISIBLE
            }
            "KGY" -> {
                mBinding.llTwoHomeFre.visibility = View.VISIBLE
                mBinding.llSelect.visibility = View.VISIBLE
            }
            "SMQ" -> {
                mBinding.llHomeFre.visibility = View.VISIBLE
                mBinding.llSelect.visibility = View.VISIBLE
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    private fun checkVersion() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) and (checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    REQUEST_CODE_EXTERNAL_STORAGE_PERMISSIONS
                )
            } else {
                PgyUpdateManager.Builder()
                    .setForced(true) //设置是否强制更新,非自定义回调更新接口此方法有用
                    .setUserCanRetry(false) //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                    .setDeleteHistroyApk(false) // 检查更新前是否删除本地历史 Apk
                    .setUpdateManagerListener(object : UpdateManagerListener {
                        override fun onNoUpdateAvailable() {
                            //没有更新是回调此方法
                            toast("已经是最新版本！")
                        }

                        override fun onUpdateAvailable(appBean: AppBean) {
                            //有更新是回调此方法
                            Log.d(
                                "pgyer", "there is new version can update"
                                        + "new versionCode is " + appBean.versionCode
                            )
                            AlertDialog.Builder(this@MainActivity).setTitle("更新提示！")
                                .setMessage("有新版本是否更新？").setPositiveButton(
                                    "更新"
                                ) { dialog, _ ->
                                    dialog.dismiss()
                                    //调用以下方法，DownloadFileListener 才有效；如果完全使用自己的下载方法，不需要设置DownloadFileListener
                                    PgyUpdateManager.downLoadApk(appBean.downloadURL)
                                }
                                .setNegativeButton("取消") { dialog, _ ->
                                    dialog.dismiss()
                                }.create().show()

                        }

                        override fun checkUpdateFailed(e: Exception) {
                            //更新检测失败回调
                            Log.e("pgyer", "check update failed ", e)
                        }
                    }) //注意 ：下载方法调用 PgyUpdateManager.downLoadApk(appBean.getDownloadURL()); 此回调才有效
                    .setDownloadFileListener(object : DownloadFileListener {
                        // 使用蒲公英提供的下载方法，这个接口才有效。
                        override fun downloadFailed() {
                            //下载失败
                            Log.e("pgyer", "download apk failed")
                        }

                        @SuppressLint("WrongConstant")
                        override fun downloadSuccessful(file: File?) {
                            Log.e("pgyer", "download apk success")
                            val intent = Intent(Intent.ACTION_VIEW)
                            file?.let {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    val apkUri: Uri =
                                        FileProvider.getUriForFile(
                                            this@MainActivity,
                                            "com.xatz.scanner.fileProvider",
                                            it
                                        )
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                    intent.setDataAndType(
                                        apkUri,
                                        "application/vnd.android.package-archive"
                                    )
                                } else {
                                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                                    val uri: Uri = Uri.fromFile(file)
                                    intent.setDataAndType(
                                        uri,
                                        "application/vnd.android.package-archive"
                                    )
                                }
                                startActivity(intent)
                            }

                        }

                        override fun onProgressUpdate(vararg p0: Int?) {
                            Log.e("pgyer", "update download apk progress : " + p0[0])
                        }

                    })
                    .register()
            }
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.llHomeFre -> startActivity(Intent(this, SalesActivity::class.java))
            R.id.llSelect -> startActivity(Intent(this, BarcodeQueryActivity::class.java))
            R.id.clDoormanReviewLayout -> startActivity(
                Intent(
                    this,
                    DoormanReviewActivity::class.java
                )
            )
            R.id.cvExit -> {
                AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("确定要退出登录吗？")
                    .setPositiveButton("确定") { dialog, _ ->
//                        edit.putBoolean(Constant.isLogin, false)
//                        edit.commit()
                        dialog.dismiss()
//                        finish()
//                        startActivity(Intent(this, LoginActivity::class.java))
                        exitDialog()
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }.show()
            }
            R.id.clVersion -> {
                checkVersion()
            }
            R.id.tvText -> {
                if (userAccount == "55001") {
                    startActivity(
                        Intent(
                            this,
                            DoormanReviewActivity::class.java
                        )
                    )
                } else {
                    startActivity(Intent(this, SalesActivity::class.java))
                }
            }
            R.id.clFourLayout -> {
                // 移库收货
                startActivity(Intent(this, ReceivingGoodsActivity::class.java))
            }
            R.id.llTwoHomeFre -> {
                // 到货确认-成品库
                startActivity(Intent(this, ArrivalConfirmationActivity::class.java))
            }
            R.id.llMovingStacking2 -> {
                // 到货确认-检斤
                startActivity(Intent(this, ArrivalConfirmCheckWeightActivity::class.java))
            }
            R.id.llMovingStacking -> {
                // 移库倒垛
                startActivity(Intent(this, WarehouseReceiptActivity::class.java))
            }
            R.id.llSoldStockOut -> {
                // 已售出库
                startActivity(Intent(this, SoldStockOutActivity::class.java))
            }
        }
    }

    private fun exitDialog() {
        val dialogView = DialogExitLoginBinding.inflate(layoutInflater)
        val exitDialog = Dialog(this)
        exitDialog.setContentView(dialogView.root)
        exitDialog.show()
        dialogView.btnClose.setOnClickListener { exitDialog.dismiss() }
        dialogView.btnFinish.setOnClickListener {

            val numIn1Et = dialogView.numIn1Et.text.toString()
            val numIn2Et = dialogView.numIn2Et.text.toString()
            val numIn3Et = dialogView.numIn3Et.text.toString()
            val numIn4Et = dialogView.numIn4Et.text.toString()

            if (numIn1Et != "2" || numIn2Et != "5" || numIn3Et != "8" || numIn4Et != "0") {
                toast("请输入正确的验证码！")
                return@setOnClickListener
            }

            exitDialog.dismiss()
            edit.putBoolean(Constant.isLogin, false)
            edit.commit()
            finish()
            startActivity(Intent(this, LoginActivity::class.java))
        }

        dialogView.numIn1Et.addTextChangedListener {
            if (it?.length == 1) {
                dialogView.numIn2Et.requestFocus()
            }
        }

        dialogView.numIn2Et.addTextChangedListener {
            if (it?.length == 1) {
                dialogView.numIn3Et.requestFocus()
            }
        }

        dialogView.numIn3Et.addTextChangedListener {
            if (it?.length == 1) {
                dialogView.numIn4Et.requestFocus()
            }
        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Timber.e(keyCode.toString())
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if (System.currentTimeMillis() - mExitTime > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis()
            } else {
                mExitTime = 0L
                //小于2000ms则认为是用户确实希望退出程序
                moveTaskToBack(true)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    @SuppressLint("NewApi")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>, grantResults: IntArray
    ) {
        when (requestCode) {
            REQUEST_CODE_EXTERNAL_STORAGE_PERMISSIONS -> {
                if (grantResults[0] and (grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
                    checkVersion()

                } else {
                    Toast.makeText(this, "请允许获取存储权限！", Toast.LENGTH_SHORT).show()
                }
            }
            else -> {
                super.onRequestPermissionsResult(
                    requestCode, permissions,
                    grantResults
                )
            }
        }
    }

}